const db = require("../db")
const date = require("silly-datetime");
const today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss'); // 2019-01-01
const lodash = require("lodash")



function filterData(role_rights, rights) {
    var permissionsResult = {};
    for (let i = 0; i < role_rights.length; i++) {
        let rightId = role_rights[i]
        if (rights[rightId].level == 1) {
            let temp = {
                'id': rights[rightId].id,
                'rightName': rights[rightId].rightName,
                'children': []
            }
            permissionsResult[rightId] = temp
        }
        else if(permissionsResult.hasOwnProperty(rights[rightId].pid)){
            permissionsResult[rights[rightId].pid].children.push(rights[rightId])
        }else{
            let temp = {
                'id': rights[rightId].pid,
                'rightName': rights[ rights[rightId].pid].rightName,
                'children': [{
                    'id': rights[rightId].id,
                    'rightName': rights[ rightId].rightName,
                }]
            }
            permissionsResult[rightId] = temp
        }
    }

    return permissionsResult

}
module.exports = {
    // 获取所有角色
    getRole: (req, res) => {
        db.query('select roleName as label, id as value from role where is_delete = 0' , function (err, result) {
            if (err) return res.cc(err)
            return res.send({
                code: 200,
                msg: "获取角色列表成功",
                data: [...result]
            })
        })
    },
    // 添加角色
    addRole: (req, res) => {
        const Role = req.body
        Role['is_delete'] = 0
        Role['createTime'] = today
        db.query('insert into role set ?', Role, function (err, result) {
            if (err) return res.cc(err)
            if (result.affectedRows != 1) return res.cc("新增角色失败！")
            return res.send({
                code: 200,
                msg: "新增角色成功"
            })
        })
    },
    // 分页获取角色
    getRoleByPage: (req, res) => {
        let queryInfo = req.body
        let sql = `select id,roleName,createTime,role_right, comment from role where is_delete = 0 `
        let start = parseInt(queryInfo.num * (queryInfo.page - 1))
        let end = queryInfo.page * queryInfo.num
        if (queryInfo.query != '') {
            sql += ` and roleName like '${queryInfo.query}'`
        }
        sql += ` limit ${start},${end} ; select count(*) as total from role;`
        db.query(sql, function (err, roles) {
            if (err) return res.cc(err)
            db.query("select * from userright", function (err, rights) {
                if (err) return res.cc(err)
                for (idx in roles[0]) {
                    if(roles[0][idx].role_right!= null){
                        let role_rights = roles[0][idx].role_right.split(',')
                        roles[0][idx]['children'] =lodash.values(filterData(role_rights, lodash.keyBy(rights, 'id'))) 
                    }

                }
                return res.send({
                    code: 200,
                    msg: "获取角色列表成功！",
                    count: roles[1][0].total,
                    data: [...roles[0]]
                })
            })

        })
    },
    // 通过id获取角色详情
    getRoleDetail: (req, res) => {
        let id = req.body.id
        let sql = `select role_right from role where id = ?`
        db.query(sql, id, function (err, result) {
            if (err) return res.cc(err)
            let data = result[0].role_right != null ?result[0].role_right.split(","):[]
            res.send({
                code: 200,
                msg: "获取角色详情成功！",
                data: data
            })
        })

    },
    // 获取角色用户
    getUserRole:(req,res)=>{
        let id = req.body.id
        let page = req.body.page
        let num = req.body.num
        let sql = `select username,email,createTime from user where roleId = ${id} limit ${parseInt((page -1)*num)},${page*num};select count(*) as count from user where roleId = ${id};`
        db.query(sql,function(err,result){
            if(err) return res.cc(err)
            return res.send({
                code:200,
                msg:"获取角色用户成功！",
                total:result[1][0].count,
                data:[...result[0]]
            })
        })
    },
    delRole:(req,res) =>{
        let id = req.body.id
        let sql = `update role set is_delete = 1 where id = ${id}`
        db.query(sql,function(err,result){
            if(err) return res.cc(err)
            if(result.affectedRows != 1) return res.cc("删除用户失败")
            return res.cc("删除用户成功",200)

        })

    }

}